package config

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"log"
	"time"
)

var (
	MySql *gorm.DB
)

func ConnectMySql() {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		GetConfiguration().Mysql.UserName, GetConfiguration().Mysql.PassWord,
		GetConfiguration().Mysql.Host, GetConfiguration().Mysql.Port,
		GetConfiguration().Mysql.DataBase)
	db, err := gorm.Open("mysql", dsn)
	if err != nil {
		log.Panicln("数据库连接错误", err.Error())
	}

	db.DB().SetMaxIdleConns(GetConfiguration().Mysql.MaxIdleConns)
	db.DB().SetMaxOpenConns(GetConfiguration().Mysql.MaxOpenConns)
	db.DB().SetConnMaxLifetime(time.Second * time.Duration(GetConfiguration().Mysql.ConnMaxLifetime))
	db.LogMode(true)
	MySql = db
}

func DisConnectMySql() {
	if err := MySql.Close(); err != nil {
		log.Panicln("关闭数据库错误", err.Error())
	}
}
